from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api import deps
from app.schemas import user as schemas
from app.database.models.base import User
from app.core.security import get_password_hash

router = APIRouter()

@router.get("/", response_model=List[schemas.User])
def read_users(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取用户列表"""
    # 系统管理员可以查看所有用户
    if current_user.role == "admin":
        users = db.query(User).offset(skip).limit(limit).all()
    # 旅行社管理员只能查看本工作区用户
    elif current_user.role == "manager":
        users = db.query(User).filter(
            User.workarea_id == current_user.workarea_id
        ).offset(skip).limit(limit).all()
    else:
        raise HTTPException(status_code=403, detail="Not enough permissions")
    return users

@router.post("/", response_model=schemas.User)
def create_user(
    *,
    db: Session = Depends(deps.get_db),
    user_in: schemas.UserCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新用户"""
    try:
        if not current_user.role == "admin":
            raise HTTPException(status_code=403, detail="Not enough permissions")
        
        # 检查用户名是否已存在
        if db.query(User).filter(User.username == user_in.username).first():
            raise HTTPException(
                status_code=400,
                detail="Username already registered"
            )
        
        # 如果提供了邮箱，检查邮箱是否已存在
        if user_in.email and db.query(User).filter(User.email == user_in.email).first():
            raise HTTPException(
                status_code=400,
                detail="Email already registered"
            )
        
        # 准备用户数据
        user_data = {
            "username": user_in.username,
            "email": user_in.email or "",
            "full_name": user_in.full_name or "",
            "role": user_in.role or "user",
            "workarea_id": user_in.workarea_id,
            "is_active": user_in.is_active if user_in.is_active is not None else True,
            "hashed_password": get_password_hash(user_in.password)
        }
        
        # 创建用户
        user = User(**user_data)
        db.add(user)
        db.commit()
        db.refresh(user)
        return user
    except Exception as e:
        db.rollback()
        print(f"Error creating user: {str(e)}")  # 添加日志
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{user_id}", response_model=schemas.User)
def read_user(
    user_id: int,
    current_user: User = Depends(deps.get_current_active_user),
    db: Session = Depends(deps.get_db),
) -> Any:
    """获取特定用户信息"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    
    # 权限检查
    if current_user.role == "admin":
        return user
    elif current_user.role == "manager":
        if user.workarea_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")
        return user
    elif current_user.id == user_id:
        return user
    raise HTTPException(status_code=403, detail="Not enough permissions")

@router.put("/{user_id}", response_model=schemas.User)
def update_user(
    *,
    db: Session = Depends(deps.get_db),
    user_id: int,
    user_in: schemas.UserUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新用户信息"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    # 权限检查
    if current_user.role == "admin":
        pass
    elif current_user.role == "manager":
        if user.workarea_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")
        # 不能修改用户的工作区
        if user_in.workarea_id and user_in.workarea_id != user.workarea_id:
            raise HTTPException(status_code=403, detail="Cannot change user's workarea")
        # 不能将用户升级为管理员
        if user_in.role == "admin":
            raise HTTPException(status_code=403, detail="Cannot promote to admin")
    elif current_user.id == user_id:
        # 用户只能修改自己的某些信息
        allowed_fields = {"email", "password"}
        for field in user_in.dict(exclude_unset=True).keys():
            if field not in allowed_fields:
                raise HTTPException(
                    status_code=403,
                    detail=f"Cannot modify field: {field}"
                )
    else:
        raise HTTPException(status_code=403, detail="Not enough permissions")

    # 更新用户信息
    update_data = user_in.dict(exclude_unset=True)
    if update_data.get("password"):
        update_data["hashed_password"] = get_password_hash(update_data.pop("password"))
    
    for field, value in update_data.items():
        setattr(user, field, value)

    db.add(user)
    db.commit()
    db.refresh(user)
    return user

@router.delete("/{user_id}")
def delete_user(
    *,
    db: Session = Depends(deps.get_db),
    user_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除用户"""
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    # 权限检查
    if current_user.role == "admin":
        pass
    elif current_user.role == "manager":
        if user.workarea_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")
        if user.role == "admin":
            raise HTTPException(status_code=403, detail="Cannot delete admin user")
    else:
        raise HTTPException(status_code=403, detail="Not enough permissions")

    db.delete(user)
    db.commit()
    return {"ok": True} 